import {
  defaultadd,
  onePurchase
} from '../../../api.js'
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    full_name: '',
    peer_price: '',
    pic: '',
    defaultadd: '',
    product_ids: '',
    leave: '',
    guojia: '',
    price:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let pro = decodeURIComponent(options.product)
    let prod = pro.replace(/\s*/g, "")
    let product = JSON.parse(prod)
    var that = this
    console.log(product)
    this.setData({
      full_name: product[0].full_name,
      peer_price: product[0].peer_price,
      price: product[0].price,
      pic: product[0].pic,
      product_ids: product[0].id,
      guojia: product[0].business_country
    })
    defaultadd({
      token: app.globalData.userInfo.token
    }).then(res => {
      if (res.data.code == 666) {
        console.log(res.data.data)
        if (res.data.data.length == 0) {
          that.setData({
            defaultadd: ''
          })
        } else {
          that.setData({
            defaultadd: res.data.data[0]
          })
        }
      } else if (res.data.code == 111111) {
        wx.showToast({
          title: '登录失效，请重新登录',
          icon: 'none',
        })
        setTimeout(function () {
          wx.reLaunch({
            url: '/pages/user/login/login',
          })
        }, 1500)
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  addChoice: function () {
    wx.navigateTo({
      url: '/pages/public/myadd/myadd?addChoice=0',
    })
  },
  leave: function (e) {
    this.setData({
      leave: e.detail.value
    })
  },
  btn_nav: function () {
    var that = this;
    if (that.data.defaultadd == '') {
      wx.showToast({
        title: '请选择地址',
        icon: 'none'
      })
      return;
    } else {
      var product_ids = that.data.product_ids;
      var delivery_id = that.data.defaultadd.id;
      var total_price = that.data.peer_price;
      var leave = that.data.leave;
      onePurchase({
        token: app.globalData.userInfo.token,
        product_ids: product_ids,
        delivery_id: delivery_id,
        total_price: total_price,
        remark: leave
      }).then(res => {
        if (res.data.code == 666) {
          wx.redirectTo({
            url: '/pages/public/payment/payment?order=' + res.data.data.batchcode + '&type=1',
          })
        } else if (res.data.code == 111111) {
          wx.showToast({
            title: '登录失效，请重新登录',
            icon: 'none',
          })
          setTimeout(function () {
            wx.reLaunch({
              url: '/pages/user/login/login',
            })
          }, 1500)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      })
    }
  }
})